package org.dinnermate.gui.trackers;

import java.sql.SQLException;
import java.util.LinkedList;

import net.java.ao.EntityManager;

import org.dinnermate.food.Ingredient;
import org.dinnermate.food.MenuItemIngredient;
import org.dinnermate.menu.MenuItem;

public class TrackIngredients
{	
	private Ingredient ingredient;
	private float quantity;
	
	public TrackIngredients(Ingredient ingredient, float quantity){
		this.ingredient = ingredient;
		this.quantity = quantity;
	}
	
	public Ingredient getIngredient(){
		return ingredient;
	}
	
	public float getQuantity(){
		return quantity;
	}
	
	public static void removeIngredient(LinkedList<TrackIngredients> mapIngredients, Ingredient badIngredient){
		for(int i = 0; i < mapIngredients.size(); i++){
			if(mapIngredients.get(i).getIngredient().equals(badIngredient)){
				mapIngredients.remove(i);
				MenuItemIngredient[] miis;
				
			}
		}
	}
	
	public static void removeIngredient(LinkedList<TrackIngredients> mapIngredients, Ingredient badIngredient, MenuItem mi, EntityManager em){
		for(int i = 0; i < mapIngredients.size(); i++){
			if(mapIngredients.get(i).getIngredient().equals( badIngredient)){
				mapIngredients.remove(i);
				MenuItemIngredient[] miis;
				try
				{
					miis = em.find(MenuItemIngredient.class);
					for(int j = 0; j < miis.length; j++){
						if(miis[j].getMenuItem() == mi && miis[j].getIngredient() == badIngredient){
							em.delete(miis[j]);
						}
					}
				}
				catch (SQLException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}
	
	/**
	 * Returns true if ingredient exists in the MenuItemIngredient array miis, false otherwise
	 * 
	 * @param miis
	 * @param ingredient
	 * @return
	 */
	public static boolean duplicateIngredient(MenuItemIngredient[] miis, Ingredient ingredient){
		boolean duplicateIngredient = false;
		
		for(int i = 0; i < miis.length; i++){
			if(miis[i].getIngredient().equals(ingredient)){
				duplicateIngredient = true;
				break;
			}
		}
		
		return duplicateIngredient;
	}
	
	public static void createIngredientMap(LinkedList<TrackIngredients> mapIngredients, MenuItemIngredient[] miis){
		for(int i = 0; i < miis.length && miis[i] != null; i++){
			try{
				mapIngredients.add(new TrackIngredients(miis[i].getIngredient(), miis[i].getQuantity()));
			}
			catch(NullPointerException e){
				break;
			}
		}
	}
}
